package competition.controller;

import competition.BaseDao;
import competition.dao.UserDao;
import competition.po.*;
import competition.vo.Upload;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/22/022.
 */

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseDao {

    @Resource(name = "userDao")
    private UserDao userDao;

    /**
     * 001.管理员登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "adminLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map adminLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) {
//        Cookie cc = new Cookie("username","hzh");
        Date date = new Date();
        Long time = date.getTime();
        response.setHeader("admin", time.toString());
//        System.out.println(date.getTime());
//        System.out.println(response.getHeaderNames());
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TAdminUserEntity.class);
        Criterion c1 = Restrictions.eq("username", username);
        Criterion c2 = Restrictions.eq("password", password);
        criteria.add(c1);
        criteria.add(c2);
        List<TAdminUserEntity> list = criteria.list();
        Map map = new HashMap();

        if (list.size() != 0) {
            HttpSession user_session = request.getSession();
            user_session.setAttribute("login", "true");
//            Cookie cookie[]=request.getCookies();
//            for (Cookie cookie1:cookie) {
//                System.out.println(cookie1.getValue());
//
//            }


            map.put("message", "管理员登录成功");
            map.put("status", 200);
        } else {
            map.put("message", "管理员登录失败");
            map.put("status", 199);
        }
        return map;
    }

    /**
     * 002.管理员发布场次
     *
     * @param screen
     * @return
     */
    @RequestMapping(value = "addScreen", method = RequestMethod.POST)
    @ResponseBody
    public Map addScreen(@RequestParam String screen, HttpServletRequest request) {

        Map map = new HashMap();
        if (!if_keep(request)) {
            map.put("message", "无权限访问");
            return map;
        }


        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        TTradesScreenEntity tTradesScreenEntity = new TTradesScreenEntity();
        tTradesScreenEntity.setScreen(screen);

        try {
            session.save(tTradesScreenEntity);
            transaction.commit();
            map.put("message", "添加场次成功");
            map.put("status", 200);
            return map;
        } catch (Exception e) {
            transaction.rollback();
        }
        map.put("message", "添加场次失败");
        map.put("status", 199);
        return map;
    }

    /**
     * 003.管理员发布新闻
     *
     * @param img
     * @param title
     * @param content
     * @param request
     * @return
     */
    @RequestMapping(value = "publishNews", method = RequestMethod.POST)
    @ResponseBody
    public Map publishNews(@RequestParam MultipartFile img, @RequestParam String title, @RequestParam String content, HttpServletRequest request) {
        Map map = new HashMap();
        if (!if_keep(request)) {
            map.put("message", "无权限访问");
            return map;
        }

        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();

        TNewsEntity tNewsEntity = new TNewsEntity();
        tNewsEntity.setContent(content);
        tNewsEntity.setTitle(title);

        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tNewsEntity.setPublishTime(ft.format(dNow).toString());


        String picture = Upload.upload(img, request);
        tNewsEntity.setPicture(picture);
        try {
            session.save(tNewsEntity);
            transaction.commit();
            map.put("message", "添加新闻成功");
            map.put("status", 200);
            return map;
        } catch (Exception e) {
            transaction.rollback();
        }
        map.put("message", "添加新闻失败");
        map.put("status", 199);
        return map;
    }

    @RequestMapping(value = "addAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map addAccount(@RequestParam String username, @RequestParam String money, HttpServletRequest request) {
        Map map = new HashMap();
        if (!if_keep(request)) {
            map.put("message", "无权限访问");
            return map;
        }

        List<TUsersEntity> list = (List<TUsersEntity>) userDao.isExist(username).get("object");
        int user_id = list.get(0).getId();

        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        TUsersEntity tUsersEntity = session.load(TUsersEntity.class, user_id);
        BigDecimal addMoney = BigDecimal.valueOf(Double.parseDouble(money));
        tUsersEntity.setMoney(tUsersEntity.getMoney().add(addMoney));  //加钱


        TUsersRecordEntity tUsersRecordEntity = new TUsersRecordEntity();
        tUsersRecordEntity.setUserId(user_id);
        tUsersRecordEntity.setCharge(addMoney);
        tUsersRecordEntity.setProfit("收入");
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tUsersRecordEntity.setTime(ft.format(dNow).toString());

        try {
            session.update(tUsersEntity);
            session.save(tUsersRecordEntity);
            transaction.commit();
            map.put("message", "加钱成功");
            map.put("status", 200);
            return map;
        } catch (Exception e) {
            transaction.rollback();
        }
        map.put("message", "加钱失败");
        map.put("status", 199);
        return map;


    }


    @RequestMapping(value = "subAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map subAccount(@RequestParam String username, @RequestParam String money, HttpServletRequest request) {

        Map map = new HashMap();
        if (!if_keep(request)) {
            map.put("message", "无权限访问");
            return map;
        }


        List<TUsersEntity> list = (List<TUsersEntity>) userDao.isExist(username).get("object");
        int user_id = list.get(0).getId();

        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        TUsersEntity tUsersEntity = session.load(TUsersEntity.class, user_id);
        BigDecimal subMoney = BigDecimal.valueOf(Double.parseDouble(money));
        if (tUsersEntity.getMoney().compareTo(subMoney) < 0) {
            map.put("message", "余额不足");
            map.put("status", 199);
            return map;
        }
        tUsersEntity.setMoney(tUsersEntity.getMoney().subtract(subMoney));  //加钱


        TUsersRecordEntity tUsersRecordEntity = new TUsersRecordEntity();
        tUsersRecordEntity.setUserId(user_id);
        tUsersRecordEntity.setCharge(subMoney);
        tUsersRecordEntity.setProfit("支出");
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tUsersRecordEntity.setTime(ft.format(dNow).toString());


        try {
            session.update(tUsersEntity);
            session.save(tUsersRecordEntity);
            transaction.commit();
            map.put("message", "提款成功");
            map.put("status", 200);
            return map;
        } catch (Exception e) {
            transaction.rollback();
        }
        map.put("message", "提款失败");
        map.put("status", 199);
        return map;


    }

    public boolean if_keep(HttpServletRequest request) {
        if (request.getHeader("admin") == null) {
            return false;
        }
        Long cook = Long.parseLong(request.getHeader("admin"));

        Date date = new Date();
        Long time = date.getTime();
        Long value = new Long(5 * 24 * 60 * 60 * 1000);
        Long ha = time - cook;


        if (ha > value) {
            return false;
        }

        return true;
    }


}
